package com.zbxx.container.websocket.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author 万仁杰
 * @date 2019/05/23
 */
@ServerEndpoint("/socket/{userId}")
@Slf4j
@Component
public class SocketServer {


    /**
     *  在线人数
     */
    private static int onlineCount;


    private static ConcurrentHashMap<Integer,Session> serverMap = new ConcurrentHashMap();

    private Session session;

    private Integer userId;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId")Integer id){
        log.info("建立了一个连接id:{}",id);
        this.session = session;
        this.userId = id;
        serverMap.put(id,this.session);
        incrementOnline();
        log.info("总在线人数:{}",getOnlineNumber());
    }

    @OnClose
    public void onClose(){
        log.info("断开连接id:{}",this.userId);
        serverMap.remove(this.userId);
        decrementOnline();
        log.info("总在线人数:{}",getOnlineNumber());
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        log.info("收到客户端的消息:{}",message);
      sendMessageAll(this.userId+":"+message);
    }

    @OnError
    public void onError( Throwable error){
        log.info("发生错误:{}",error.getMessage());
    }

    private void sendMessageAll(String message){
        if(!CollectionUtils.isEmpty(serverMap)){
           Set<Map.Entry<Integer,Session>> sessionSet = serverMap.entrySet();
           sessionSet.forEach(entry-> {
               try {
                   entry.getValue().getBasicRemote().sendText(message);
               } catch (IOException e) {
                   e.printStackTrace();
               }
           });
        }
    }

    private synchronized int getOnlineNumber(){
        return onlineCount;
    }

    private synchronized void decrementOnline(){
        onlineCount--;
    }

    private synchronized void incrementOnline(){
        onlineCount++;
    }


}
